package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"strconv"
	"zlxBook/Dao"
	"zlxBook/Response"
	"zlxBook/db"
	"zlxBook/model"
)

//继承PostController
type PostControllerInferface interface {
	RestPostController
}
type PostController struct {
	DB *gorm.DB
	PostControllerInferface
}

func NewPostController() PostController {
	db.DB.AutoMigrate(model.Post{})
	return PostController{DB: db.DB}

}

//文章的CRUD
func (p PostController) AddPost(context *gin.Context) {
	userID := context.PostForm("user_id")
	categoryID := context.PostForm("category_id")
	title := context.PostForm("title")
	headImg := context.PostForm("head_img")
	content := context.PostForm("content")
	uuserID, _ := strconv.Atoi(userID)
	ucategoryID, _ := strconv.Atoi(categoryID)
	post := &model.Post{
		UserId:     uint(uuserID),
		CategoryId: uint(ucategoryID),
		Title:      title,
		HeadImg:    headImg,
		Content:    content,
	}
	Dao.AddPost(post)
	context.JSON(http.StatusOK, Response.MessageMaker("增加数据成功"))
}

func (p PostController) GetPost(context *gin.Context) {
	posts := []*model.Post{}
	posts, err := Dao.GetPost()
	if err != nil {
		panic("获取文章失败")
	}
	context.JSON(http.StatusOK, gin.H{"msg": posts})

}
func (p PostController) UpdatePost(context *gin.Context) {
	postId := context.Params.ByName("id")

	var post model.Post
	if db.DB.Where("id=?", postId).First(&post).RecordNotFound() {
		panic("文章不存在")
		return
	}
	user, _ := context.Get("user") // 判断当前用户是否为文章的作者
	userId := user.(model.User).ID
	if userId != post.UserId {
		panic("文章不属于你！")
		return
	}
	err := db.DB.Model(&post).Update(post).Error // Update post
	if err != nil {
		panic("更新失败")
	}
	context.JSON(http.StatusOK, Response.MessageMaker("更新成功"))
}

func (p PostController) DeletePostByID(ctx *gin.Context) {
	postId := ctx.Params.ByName("id") // Get the path id
	var post model.Post
	if db.DB.Where("id=?", postId).First(&post).RecordNotFound() {
		panic("文章不存在")
		return
	}
	user, _ := ctx.Get("user") // 获取登录用户
	userId := user.(model.User).ID
	if userId != post.UserId { // 判断当前用户是否为文章的作者
		panic("文章不属于你")
		return
	}
	db.DB.Delete(&post)
	Response.Success(ctx, Response.MessageMaker("成功"), "w")
}
